package com.facebank.usersupport.service.impl;

import com.facebank.usersupport.common.TravelSiteEnum;
import com.facebank.usersupport.mapper.usersupport.usersupport.ActivityMapper;
import com.facebank.usersupport.mapper.usersupport.usersupport.ActivityTripMapper;
import com.facebank.usersupport.mapper.usersupport.usersupport.RouteMapper;
import com.facebank.usersupport.mapper.usersupport.usersupport.TripMapper;
import com.facebank.usersupport.model.Activity;
import com.facebank.usersupport.model.ActivityTrip;
import com.facebank.usersupport.model.Route;
import com.facebank.usersupport.model.Trip;
import com.facebank.usersupport.service.ITravelDetailService;
import com.facebank.usersupport.util.TravelSpiderUtil;
import com.facebank.usersupport.util.WebSpiderUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class TravelDetailServiceImpl implements ITravelDetailService {

    @Autowired
    private RouteMapper routeMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private TripMapper tripMapper;
    @Autowired
    private ActivityTripMapper activityTripMapper;

    public int getDetail(String url,int page) {

        Route route = new Route();
        Activity activity = new Activity();
        ActivityTrip activityTrip = new ActivityTrip();

        try{
            String result = WebSpiderUtil.crawl(url);
            //将空格和换行替换成java识别的符号
            result = result.replace("&nbsp;", "  ").replace("<br />", "\n").replace("<br/>","\n");
            Document doc = Jsoup.parse(result);
            doc.setBaseUri(url);
            Map<String, String> contexts = TravelSpiderUtil.getContext(TravelSiteEnum.getEnumByUrl(url));
            String errorSelector = contexts.get("error-page");
            if("很抱歉，您要访问的页面不存在！".equals(doc.select(errorSelector).text())){
                return 0;
            }
            //获取路线标题
            String routeNameSelector = contexts.get("route-name-selector");
            if(doc.select(routeNameSelector).isEmpty()){
                return 0;
            }
            String routeName = doc.select(routeNameSelector).first().text();
            //获取路线类型
            short type = 2;
            String routeTypeSelector = contexts.get("route-type-selector1");
            String[] splits = routeTypeSelector.split(",");
            splits = parseSelector(splits);
            if(doc.select(splits[0]).isEmpty()){
                return 0;
            }
            if("国内".equals(doc.select(splits[0]).get(Integer.parseInt(splits[1])).text())){
                type = 1;
                routeTypeSelector = contexts.get("route-type-selector2");
                splits = routeTypeSelector.split(",");
                splits = parseSelector(splits);
                if("广东".equals(doc.select(splits[0]).get(Integer.parseInt(splits[1])).text())){
                    type = 0;
                }
            }
            //路线介绍
            String routeDetailSelector = contexts.get("route-detail-selector");
            if(doc.select(routeDetailSelector).isEmpty()){
                return 0;
            }
            String routeDetail = doc.select(routeDetailSelector).text();
            //产品主图
            String imgSelector = contexts.get("route-img-selector");
            splits = imgSelector.split(",");
            splits = parseSelector(splits);
            if(doc.select(splits[0]).isEmpty()){
                return 0;
            }
            String img = doc.select(splits[0]).get(Integer.parseInt(splits[1])).absUrl("href");

            //其他花费详情
            Elements elements = doc.select(TravelSpiderUtil.getContext(TravelSiteEnum.getEnumByUrl(url)).get("route-cost-selector"));
            if(elements.size()<=1){
                return 0;
            }
            String cost = elements.get(0).text();
            //温馨提示
            String prompt = elements.get(1).text();
            //价格
            // 分开为成人与儿童价格
            String priceSelector = contexts.get("activity-price-selector");
            if(doc.select(priceSelector).isEmpty()||"".equals(doc.select(priceSelector).first().text())){
                return 0;
            }
            int price = Integer.parseInt(doc.select(priceSelector).first().text());

            //行程天数
//            String dateSelector = contexts.get("activity-date-selector");
//            if(doc.select(dateSelector).isEmpty()){
//                return 0;
//            }
//            int date = Integer.parseInt(doc.select(dateSelector).first().text());
            int date = 0;

            int id = -1;
            if(doc.select(contexts.get("trip-day1-selector")).isEmpty()){
               return 0;
            }
            if(!doc.select(contexts.get("trip-day1-selector")).isEmpty()){
                id = 1;
                if(null != tripMapper.selectAllLimit1()){
                    id = tripMapper.selectAllLimit1().getTripId()+1;
                }
                for(int i = 0;;date = i){
                    Trip trip = new Trip();
                    StringBuffer sb = new StringBuffer(contexts.get("trip-day-selector"));
                    sb.append(++i+" ");
                    sb.append(contexts.get("trip-day-title-selector"));
                    if(doc.select(sb.toString()).isEmpty()){
                        break;
                    }
                    String title = doc.select(sb.toString()).text();
                    sb.delete(sb.length()-contexts.get("trip-day-title-selector").length(),sb.length());
                    sb.append(contexts.get("trip-day-detail-selector"));
                    if(doc.select(sb.toString()).isEmpty()){
                        return 0;
                    }
                    String detail = doc.select(sb.toString()).text();
                    trip.setTripId(id);
                    trip.setDateNo(i);
                    trip.setTitle(title);
                    trip.setDetail(detail);
                    tripMapper.insertSelective(trip);
                }
            }

            //路线对象
            if(!routeMapper.selectRouteList(routeName,null,null,null).isEmpty()){
                return 0;
            }
            route.setRouteName(routeName);
            route.setRouteType(Long.valueOf(type));
            route.setTitle(routeName);
            route.setDetail(routeDetail);
            route.setImg(img);
            route.setCost(cost);
            route.setPrompt(prompt);
            route.setCreateTime(System.currentTimeMillis());
            route.setUpdateTime(System.currentTimeMillis());

            //活动对象
            activity.setRouteName(routeName);
            activity.setRouteType(type);
            activity.setTitle(routeName);
            activity.setDetail(routeDetail);
            activity.setImg(img);
            activity.setDaytime(Long.valueOf(page));
            activity.setDate(date);
            activity.setAdultPrice(price);
            activity.setChildPrice(price/2);
            activity.setStock(100);
            activity.setCost(cost);
            activity.setPrompt(prompt);
            activity.setCollectionSite("DGUT");
            activity.setCreateTime(System.currentTimeMillis());
            activity.setUpdateTime(System.currentTimeMillis());

            routeMapper.insertSelective(route);
            activityMapper.insertSelective(activity);
            //System.out.println(activity.getId());
            if(id != -1){
                activityTrip.setActivityId(Long.valueOf(activity.getId()));
                activityTrip.setId(Long.valueOf(id));
                activityTrip.setGmtCreate(new Date());
                activityTrip.setGmtModify(new Date());
                activityTripMapper.insertSelective(activityTrip);
            }

        }catch (Exception e) {
            throw new  RuntimeException(e);
        }
        return 1;
    }

    /**
     * 获取第几个元素
     * @param splits
     * @return
     */
    private String[] parseSelector(String[] splits) {
        String[] newSplits = new String[2];
        if (splits.length == 1) {
            newSplits[0] = splits[0];
            newSplits[1] = "0";
            return newSplits;
        }else
            return splits;
    }
}
